
package com.be.beadmin.quality.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.product.entity.WorkOrderInfor;
import com.be.beadmin.project.entity.*;
import com.be.beadmin.project.repository.*;
import com.be.beadmin.quality.dto.input.InspectionInfoAllEx;
import com.be.beadmin.quality.dto.input.InspectionTotal;
import com.be.beadmin.quality.dto.input.ProductQualityDto;
import com.be.beadmin.quality.dto.output.InspectionStandardEx;
import com.be.beadmin.quality.dto.output.ProductQualityEx;
import com.be.beadmin.quality.dto.output.ProductQualityInspectionAllInfoEx;
import com.be.beadmin.quality.dto.output.ProductQualityInspectionByPage;
import com.be.beadmin.quality.entity.*;
import com.be.beadmin.quality.mapper.*;
import com.be.beadmin.quality.repository.*;
import com.be.beadmin.quality.service.*;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.service.DictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @description 服务实现
* @author zjm
* @date 2023-05-16
**/
@Service
@RequiredArgsConstructor
public class ProductQualityServiceImpl implements ProductQualityService {

    @Autowired
    private  ProductQualityRepository productQualityRepository;
    @Autowired
    private  ProductQualityMapper productQualityMapper;
    @Autowired
    private  ProductQualityMapperEx productQualityExMapper;

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private TeamInfoRepository teamInfoRepository;

    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private BatchPlanRepository batchPlanRepository;

    @Autowired
    private BatchProductRepository batchProductRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private InspectionTemplateRepository inspectionTemplateRepository;

    @Autowired
    private InspectionTaskRepository inspectionTaskRepository;

    @Autowired
    private DictTypeRepository dictTypeRepository;

    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private InspectionMasterValueService inspectionMasterValueService;
    @Autowired
    private InspectionItemValueService inspectionItemValueService;

    @Autowired
    private InspectionTemplateService inspectionTemplateService;

    @Autowired
    private ProductQualityInspectionRepository productQualityInspectionRepository;

    @Autowired
    private InspectionTaskService inspectionTaskService;

    @Override
    public Page<ProductQualityEx> getProductQualityByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<ProductQuality> page = productQualityRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(ProductQuality_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(ProductQuality_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<ProductQualityEx> page1 = page.map(productQualityExMapper::toEntity);
            return page1;

    }

    @Override
    public Page<ProductQualityInspection> getProductQualityInspectionByPage(ProductQualityInspectionByPage productQualityInspectionByPage) {
        String id = productQualityInspectionByPage.getProductQualityId();
        PageEntity pageEntity= productQualityInspectionByPage.getPageEntity();
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<ProductQualityInspection> page = productQualityInspectionRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(ProductQualityInspection_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(ProductQualityInspection_.productQualityId), id); //过滤为0
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(ProductQualityInspection_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        return page;
    }

    @Override
    public void addProductQuality(ProductQualityDto productQualityDto) {
            ProductQuality result = productQualityRepository.findProductQualityByIdAndDelete(productQualityDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("ProductQuality不存在,请重新查询");
            }
            ProductQuality productQuality = productQualityMapper.toEntity(productQualityDto);
            productQualityRepository.save(productQuality);
    }

    @Override
    public void addProductQualityByWos(List<WorkOrderInfor> workOrderInforList) {
        // List<ProductQuality> productQualityList=new ArrayList<>();
        //List<InspectionTask> inspectionTaskList=new ArrayList<>();
        for(WorkOrderInfor workOrderInfor:workOrderInforList){
            ProductQuality productQuality =new ProductQuality();

            productQuality.setProjectId(workOrderInfor.getInfoId());
            productQuality.setProjectName(workOrderInfor.getProjectName());

            BatchProduct product = batchProductRepository.findBatchProductByIdAndDelete(workOrderInfor.getBatchProductId(), 0);
            BatchPlan batchPlan = batchPlanRepository.findBatchPlanById(product.getBatchPlanId());
            productQuality.setBatchDeliveryDate(batchPlan.getBatchDeliveryDate());

            productQuality.setWo(workOrderInfor.getWo());
            productQuality.setProjectCode(workOrderInfor.getProjectCode());
            productQuality.setBatchPlanCode(batchPlan.getBatchPlanCode());
            productQuality.setCurrentBatchCode(String.valueOf(batchPlan.getCurrentBatch()));
            productQuality.setBatchCount(batchPlan.getBatchCount());


            productQuality.setProductId(workOrderInfor.getBatchProductId());
            productQuality.setProductCode(workOrderInfor.getBatchProductCode());
            productQuality.setProductType(workOrderInfor.getProductType());
            if(workOrderInfor.getProductName()==null){
                if(workOrderInfor.getProductDesc()==null){
                    BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(workOrderInfor.getBatchProductId(),0);
                    if(batchProduct.getProductDesc()!=null) productQuality.setProductDesc(batchProduct.getProductDesc());
                }else{
                    productQuality.setProductDesc(workOrderInfor.getProductDesc());
                }
            }else{
                productQuality.setProductDesc(workOrderInfor.getProductName());
            }

            productQuality.setStatus(0);



            // 关联入厂检验模板
            InspectionTemplate inspectionTemplate = inspectionTemplateRepository.
                    findInspectionTemplateByProductTypeAndTypeAndDelete(workOrderInfor.getProductType(),"柜体入厂检验",0);

            if(inspectionTemplate==null) throw new BeadminException("未找到‘"+workOrderInfor.getProductType()+"'类型的柜体入厂检验模板");

            // productQualityList.add(productQuality);
            ProductQuality productQuality1 = productQualityRepository.save(productQuality);

            InspectionTask inspectionTask =new InspectionTask();

            inspectionTask.setProductQualityId(productQuality1.getId());
            inspectionTask.setInspectionTemplateId(inspectionTemplate.getId());
            inspectionTask.setType(inspectionTemplate.getType());
            inspectionTask.setTemplateName(inspectionTemplate.getName());
            inspectionTask.setProjectCode(workOrderInfor.getProjectCode());
            inspectionTask.setInfoId(workOrderInfor.getInfoId());
            inspectionTask.setProjectName(workOrderInfor.getProjectName());
            inspectionTask.setWo(workOrderInfor.getWo());
            inspectionTask.setCurrentBatch(Integer.valueOf(productQuality1.getCurrentBatchCode()));
            inspectionTask.setBatchCount(productQuality1.getBatchCount());
            inspectionTask.setState(0);
            inspectionTask.setBatchProductCode(productQuality1.getProductCode());


           // inspectionTaskList.add(inspectionTask);

            InspectionTask inspectionTask1 = inspectionTaskRepository.save(inspectionTask);

            productQuality1.setInspectionTaskId(inspectionTask1.getId());
            productQualityRepository.save(productQuality1);


            // 生成模板对应的每个检验项和对应值
            // 生成自定义项目值
            inspectionMasterValueService.generateInspectionMasterValue(inspectionTask1,inspectionTemplate);
            // 生成检验记录表检验项目值
            inspectionItemValueService.generateInspectionItemValue(inspectionTask1,inspectionTemplate);

        }
        //productQualityRepository.saveAll(productQualityList);

        //inspectionTaskRepository.saveAll(inspectionTaskList);

    }

    @Override
    public void updateProductQuality(ProductQualityDto productQualityDto) {
            ProductQuality productQuality =  productQualityMapper.toEntity(productQualityDto);
            productQuality.setInspectTime(productQualityDto.getInspectTime());
            productQuality= productQualityRepository.save(productQuality);
            String inspection = productQuality.getInspection();

            ProductQualityInspection productQualityInspection = new ProductQualityInspection();
        if(productQuality.getId()!=null) productQualityInspection.setProductQualityId(productQuality.getId());
        if(productQuality.getInspectionTaskId()!=null) productQualityInspection.setInspectionTaskId(productQuality.getInspectionTaskId());
        if(productQuality.getWo()!=null) productQualityInspection.setWo(productQuality.getWo());

        if(productQuality.getProjectId()!=null) productQualityInspection.setProjectId(productQuality.getProjectId());
        if(productQuality.getProjectName()!=null) productQualityInspection.setProjectName(productQuality.getProjectName());
        if(productQuality.getProjectCode()!=null) productQualityInspection.setProjectCode(productQuality.getProjectCode());

        if(productQuality.getBatchPlanCode()!=null) productQualityInspection.setBatchPlanCode(productQuality.getBatchPlanCode());
        if(productQuality.getCurrentBatchCode()!=null)productQualityInspection.setCurrentBatchCode(productQuality.getCurrentBatchCode());
        if(productQuality.getBatchCount()!=null)productQualityInspection.setBatchCount(productQuality.getBatchCount());
        if(productQuality.getBatchDeliveryDate()!=null) productQualityInspection.setBatchDeliveryDate(productQuality.getBatchDeliveryDate());

        if(productQuality.getProductId()!=null)productQualityInspection.setProductId(productQuality.getProductId());
        if(productQuality.getProductType()!=null)productQualityInspection.setProductType(productQuality.getProductType());
        if(productQuality.getProductCode()!=null)productQualityInspection.setProductCode(productQuality.getProductCode());
        if(productQuality.getProductDesc()!=null)productQualityInspection.setProductDesc(productQuality.getProductDesc());


        productQualityInspection.setStatus(productQuality.getStatus());//这张表，是已检验状态
        if(productQuality.getInspection()!=null)productQualityInspection.setInspection(Integer.parseInt(productQuality.getInspection()));
        if(productQuality.getInspectTime()!=null)productQualityInspection.setInspectTime(productQuality.getInspectTime());
            if(productQuality.getInspector()!=null)productQualityInspection.setInspector(productQuality.getInspector());
            if(productQuality.getInspectorId()!=null)productQualityInspection.setInspectorId(productQuality.getInspectorId());
            if(productQuality.getMemo()!=null)productQualityInspection.setMemo(productQuality.getMemo());
            productQualityInspection=productQualityInspectionRepository.save(productQualityInspection);
//            String inspection = productQuality.getInspection();
//            if(inspection.equals("-1")|| inspection.equals("2")){
//                //检验不合格，加一条待检验记录
//                ProductQuality productQuality1 =new ProductQuality();
//
//                productQuality1.setProjectId(productQuality.getProjectId());
//                productQuality1.setProjectCode(productQuality.getProjectCode());
//                productQuality1.setProjectName(productQuality.getProjectName());
//                productQuality1.setBatchPlanCode(productQuality.getBatchPlanCode());
//                productQuality1.setBatchDeliveryDate(productQuality.getBatchDeliveryDate());
//                productQuality1.setWo(productQuality.getWo());
//                productQuality1.setCurrentBatchCode(productQuality.getCurrentBatchCode());
//                if(productQuality.getProductId()!=null)  productQuality1.setProductId(productQuality.getProductId());
//                productQuality1.setProductCode(productQuality.getProductCode());
//                productQuality1.setProductType(productQuality.getProductType());
//                if(productQuality.getProductDesc()!=null)productQuality1.setProductDesc(productQuality.getProductDesc());
//                productQuality1.setInspectTime(productQualityDto.getInspectTime());
//                productQuality1.setStatus(0);
//
//                ProductQuality productQuality2 = productQualityRepository.save(productQuality1);
//
//                InspectionTask  inspectionTask1 = inspectionTaskRepository.findInspectionTaskByProductQualityIdAndDelete(productQuality.getId(),0);
//
//                InspectionTask inspectionTask =new InspectionTask();
//
//                inspectionTask.setProductQualityId(productQuality2.getId());
//                inspectionTask.setInspectionTemplateId(inspectionTask1.getInspectionTemplateId());
//                inspectionTask.setType(inspectionTask1.getType());
//                inspectionTask.setTemplateName(inspectionTask1.getTemplateName());
//                inspectionTask.setProjectCode(inspectionTask1.getProjectCode());
//                inspectionTask.setInfoId(inspectionTask1.getInfoId());
//                inspectionTask.setProjectName(inspectionTask1.getProjectName());
//                inspectionTask.setWo(inspectionTask1.getWo());
//                inspectionTask.setCurrentBatch(inspectionTask1.getCurrentBatch());
//                inspectionTask.setBatchCount(inspectionTask1.getBatchCount());
//                inspectionTask.setState(0);
//
//                InspectionTask inspectionTask2 = inspectionTaskRepository.save(inspectionTask);
//
//                InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateByIdAndDelete(inspectionTask1.getInspectionTemplateId(),0);
//
//                // 生成模板对应的每个检验项和对应值
//                // 生成自定义项目值
//                inspectionMasterValueService.generateInspectionMasterValue(inspectionTask2,inspectionTemplate);
//                // 生成检验记录表检验项目值
//                inspectionItemValueService.generateInspectionItemValue(inspectionTask2,inspectionTemplate);
//            }
    }


    @Override
    public void delProductQuality(String id) {
        ProductQuality productQuality = productQualityRepository.findProductQualityById(id);
        productQuality.setDelete(1);
        productQualityRepository.save(productQuality);
    }

    @Override
    public void delProductQualitys (List<String> ids) { }

    @Override
    public List<User> getQualityTeamMembers(String projectId) {
        if(projectId==null)throw new BeadminException("未指定项目id");
        Info info = infoRepository.findInfoByIdAndDelete(projectId,0);
        String teamId = info.getTeamId();

        List<TeamInfo> teamInfoList = teamInfoRepository.findTeamInfosByTeamIdAndCategoryAndDelete(teamId,"检验人员",0);
        List<User> userList = new ArrayList<>();
        for(TeamInfo teamInfo:teamInfoList){
            User user  = userRepository.findUserByIdAndDelete(teamInfo.getUserId(),0);
            userList.add(user);
        }
        return userList;
    }

    @Override
    public List<InspectionStandardEx> getInspectionStandard() {
        DictType dictType = dictTypeRepository.findDictTypeByDictName("检验标准");
        HashMap<String,String> map = dictDataService.getDictDataMapByDictTypeId(dictType);
        List<InspectionStandardEx> inspectionStandardExList = new ArrayList<>();
        map.forEach((key,value) -> {
            InspectionStandardEx inspectionStandardEx = new InspectionStandardEx();
            inspectionStandardEx.setInspectionItem(key);
            inspectionStandardEx.setInspectionStandard(value);
            inspectionStandardExList.add(inspectionStandardEx);
        });
        return inspectionStandardExList;
    }

    @Override
    public ProductQualityInspectionAllInfoEx getProductQualityInspectionAllInfoByProductQualityId(String productQualityId) {
        if(productQualityId==null) throw new BeadminException("未指定入厂检id");

        ProductQuality productQuality = productQualityRepository.findProductQualityByIdAndDelete(productQualityId,0);
        String taskId;
        if(productQuality.getInspectionTaskId()==null){
            InspectionTask inspectionTask = inspectionTaskRepository.findInspectionTaskByProductQualityIdAndDelete(productQualityId,0);
            taskId = inspectionTask.getId();
        }else{
            taskId=productQuality.getInspectionTaskId();
        }


        InspectionInfoAllEx inspectionInfoAllEx = inspectionTaskService.getInspectionTaskById(taskId);

        ProductQualityInspectionAllInfoEx productQualityInspectionAllInfoEx =new ProductQualityInspectionAllInfoEx();
        productQualityInspectionAllInfoEx.setProductQuality(productQuality);
        productQualityInspectionAllInfoEx.setInspectionInfoAllEx(inspectionInfoAllEx);

        return productQualityInspectionAllInfoEx;
    }

    /**
     * 根据柜体id获取入厂检验
     *
     * @param productCode
     * @return
     */
    @Override
    public List<ProductQuality> getProductQualityByBatchProduct(String productCode) {
        List<String> list =new ArrayList<>();
        list.add("1");
        list.add("2");
        return productQualityRepository.findProductQualityByProductCodeAndDeleteAndInspectionIn(productCode,0,list);
    }




}